#send email using mailtrap in laravel
Explore tagged Tumblr posts
codehunger · 4 years ago
Text
Send Mail In Laravel Using SMTP |Laravel - 8
Send Mail In Laravel Using SMTP |Laravel – 8
In this blog we will learn about how we can send mail in Laravel using SMTP, how we can configure SMTP in Laravel, I will use mailtrap SMTP to configure the Laravel application, I will put all the SMTP details in the .env file Laravel 8 provides a mail class to send an email. you can use several drivers for sending email in Laravel 8. you can use mailtrap, SMTP, Mailgun, Postmark, Amazon SES,…
Tumblr media
View On WordPress
0 notes
itsmetacentric · 5 years ago
Link
laravel 5 8 send email,laravel 5 send email example,markdown laravel 7/6 mail, markdown laravel 7/6 email, laravel 7/6 markdown components, laravel 7/6 send email mailable, laravel 7/6 send email markdown, laravel 7/6 send mail mailable, laravel 7/6 send mail using mailable
0 notes
gadherkeyur · 5 years ago
Text
How To Send Mail Using Queue In Laravel?
How To Send Mail Using Queue In Laravel?
[vc_row][vc_column][vc_column_text]
Sending emails using laravel mail queue reduces the response time of application. Suppose you need to send multiple emails, you need to wait for some time for a server to respond. Some peoples using a job class to send mail using a queue. But it’s the not correct way. Laravel provides queue API, especially for mails.
I’m using mailtrapfor receiving mail. If you…
View On WordPress
0 notes
mbaljeetsingh · 7 years ago
Text
Understanding and Working with Files in Laravel
File uploads is one the most commonly used features on the web. From uploading avatars to family pictures to sending documents via email, we can't do without files on the web.
In today’s article will cover all the ways to handle files in Laravel. If you are new to Laravel, browse the courses or navigate to the tutorials section. After reading the article, If we left something out please let us know in the comments and we’ll update the post accordingly.
Handling of files is another thing Laravel has simplified in its ecosystem. Before we get started, we’ll need a few things. First, a Laravel project. There are a few ways to create a new Laravel project, but let's stick to composer for now.
composer create-project --prefer-dist laravel/laravel files
Where files is the name of our project. After installing the app, we’ll need a few packages installed, so, let’s get them out of the way. You should note that these packages are only necessary if you intend to save images to Amazon’s s3 or manipulate images like cropping, filters etc.
composer require league/flysystem-aws-s3-v3:~1.0 intervention/image:~2.4
After installing the dependencies, the final one is Mailtrap. Mailtrap is a fake SMTP server for development teams to test, view and share emails sent from the development and staging environments without spamming real customers. So head over to Mailtrap and create a new inbox for testing.
Then, in welcome.blade.php update the head tag to:
<meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>File uploads</title> <style> * { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; } </style>
Modify the body contents to:
<form action="/process" enctype="multipart/form-data" method="POST"> <p> <label for="photo"> <input type="file" name="photo" id="photo"> </label> </p> <button>Upload</button> </form>
For the file upload form, the enctype="multipart/form-data" and method="POST" are extremely important as the browser will know how to properly format the request. is Laravel specific and will generate a hidden input field with a token that Laravel can use to verify the form submission is legit.
If the CSRF token does not exist on the page, Laravel will show “The page has expired due to inactivity” page.
Now that we have our dependencies out of the way, let's get started.
Understanding How Laravel Handles Files
Development as we know it in 2018 is growing fast, and in most cases there are many solutions to one problem. Take file hosting for example, now we have so many options to store files, the sheer number of solutions ranging from self hosted to FTP to cloud storage to GFS and many others.
Since Laravel is framework that encourages flexibility, it has a native way to handle the many file structures. Be it local, Amazon's s3, Google's Cloud, Laravel has you covered.
Laravel's solution to this problem is to call them disks. Makes sense, any file storage system you can think of can be labeled as a disk in Laravel. To this regard, Laravel comes with native support for some providers (disks). We have: local, public, s3, rackspace, FTP etc. All this is possible because of Flysystem.
If you open config/filesystems.php you’ll see the available disks and their respected configuration.
File Uploads in Laravel
From the introduction section above, we have a form with a file input ready to be processed. We can see that the form is pointed to /process. In routes/web.php, we define a new POST /process route.
use Illuminate\Http\Request; Route::post('process', function (Request $request) { $path = $request->file('photo')->store('photos'); dd($path); });
What the above code does is grab the photo field from the request and save it to the photos folder. dd() is a Laravel function that kills the running script and dumps the argument to the page. For me, the file was saved to "photos/3hcX8yrOs2NYhpadt4Eacq4TFtpVYUCw6VTRJhfn.png". To find this file on the file system, navigate to storage/app and you’ll find the uploaded file.
If you don't like the default naming pattern provided by Laravel, you can provide yours using the storeAs method.
Route::post('process', function (Request $request) { // cache the file $file = $request->file('photo'); // generate a new filename. getClientOriginalExtension() for the file extension $filename = 'profile-photo-' . time() . '.' . $file->getClientOriginalExtension(); // save to storage/app/photos as the new $filename $path = $file->storeAs('photos', $filename); dd($path); });
After running the above code, I got "photos/profile-photo-1517311378.png".
Difference Between Local and Public Disks
In config/filesystems.php you can see the disks local and public defined. By default, Laravel uses the local disk configuration. The major difference between local and public disk is that local is private and cannot be accessed from the browser while public can be accessed from the browser.
Since the public disk is in storage/app/public and Laravel's server root is in public you need to link storage/app/public to Laravel's public folder. We can do that with our trusty artisan by running php artisan storage:link.
Uploading Multiple Files
Since Laravel doesn't provide a function to upload multiple files, we need to do that ourselves. It’s not much different from what we’ve been doing so far, we just need a loop.
First, let’s update our file upload input to accept multiple files.
<input type="file" name="photos[]" id="photo" multiple>
When we try to process this $request->file('photos'), it's now an array of UploadedFile instances so we need to loop through the array and save each file.
Route::post('process', function (Request $request) { $photos = $request->file('photos'); $paths = []; foreach ($photos as $photo) { $extension = $photo->getClientOriginalExtension(); $filename = 'profile-photo-' . time() . '.' . $extension; $paths[] = $photo->storeAs('photos', $filename); } dd($paths); });
After running this, I got the following array, since I uploaded a GIF and a PNG:
array:2 [▼ 0 => "photos/profile-photo-1517315875.gif" 1 => "photos/profile-photo-1517315875.png" ]
Validating File Uploads
Validation for file uploads is extremely important. Apart from preventing users from uploading the wrong file types, it’s also for security. Let me give an example regarding security. There's a PHP configuration option cgi.fix_pathinfo=1. What this does is when it encounters a file like https://site.com/images/evil.jpg/nonexistent.php, PHP will assume nonexistent.php is a PHP file and it will try to run it. When it discovers that nonexistent.php doesn't exists, PHP will be like "I need to fix this ASAP" and try to execute evil.jpg (a PHP file disguised as a JPEG). Because evil.jpg wasn’t validated when it was uploaded, a hacker now has a script they can freely run live on your server… Not… good.
To validate files in Laravel, there are so many ways, but let’s stick to controller validation.
Route::post('process', function (Request $request) { // validate the uploaded file $validation = $request->validate([ 'photo' => 'required|file|image|mimes:jpeg,png,gif,webp|max:2048' // for multiple file uploads // 'photo.*' => 'required|file|image|mimes:jpeg,png,gif,webp|max:2048' ]); $file = $validation['photo']; // get the validated file $extension = $file->getClientOriginalExtension(); $filename = 'profile-photo-' . time() . '.' . $extension; $path = $file->storeAs('photos', $filename); dd($path); });
For the above snippet, we told Laravel to make sure the field with a name of photo is required, a successfully uploaded file, it’s an image, it has one of the defined mime types, and it’s a max of 2048 kilobytes ~~ 2 megabytes.
Now, when a malicious user uploads a disguised file, the file will fail validation and if for some weird reason you leave cgi.fix_pathinfo on, this is not a means by which you can get PWNED!!!
If you head over to Laravel's validation page you’ll see a whole bunch of validation rules.
Moving Files to the Cloud
Okay, your site is now an adult, it has many visitors and you decide it’s time to move to the cloud. Or maybe from the beginning, you decided your files will live on separate server. The good news is Laravel comes with support for many cloud providers, but, for this tutorial, let's stick with Amazon.
Earlier we installed league/flysystem-aws-s3-v3 through composer. Laravel will automatically look for it if you choose to use Amazon S3 or throw an exception.
To upload files to the cloud, just use:
$request->file('photo')->store('photos', 's3');
For multiple file uploads:
foreach ($photos as $photo) { $extension = $photo->getClientOriginalExtension(); $filename = 'profile-photo-' . time() . '.' . $extension; $paths[] = $photo->storeAs('photos', $filename, 's3'); }
Users may have already uploaded files before you decide to switch to a cloud provider, you can check the upcoming sections for what to do when files already exist.
Note: you’ll have to configure your Amazon s3 credentials in config/filesystems.php**.**
Sending Files as Email Attachments
Before we do this, let's quickly configure our mail environment. In .env file you will see this section
MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null
We need a username and password which we can get at Mailtrap.io. Mailtrap is really good for testing emails during development as you don’t have to crowd your email with spam. You can also share inboxes with team members or create separate inboxes.
First, create an account and login:
Create a new inbox
Click to open inbox
Copy username and password under SMTP section
youtube
After copying credentials, we can modify .env to:
MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=8a1d546090493b MAIL_PASSWORD=328dd2af5aefc3 MAIL_ENCRYPTION=null
Don't bother using mine, I deleted it.
Create your mailable
php artisan make:mail FileDownloaded
Then, edit its build method and change it to:
public function build() { return $this->from('[email protected]') ->view('emails.files_downloaded') ->attach(storage_path('app/file.txt'), [ 'as' => 'secret.txt' ]); }
As you can see from the method above, we pass the absolute file path to the attach() method and pass an optional array where we can change the name of the attachment or even add custom headers. Next we need to create our email view.
Create a new view file in resources/views/emails/files_downloaded.blade.php and place the content below.
<h1>Only you can stop forest fires</h1> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Labore at reiciendis consequatur, ea culpa molestiae ad minima est quibusdam ducimus laboriosam dolorem, quasi sequi! Atque dolore ullam nisi accusantium. Tenetur!</p>
Now, in routes/web.php we can create a new route and trigger a mail when we visit it.
use App\Mail\FileDownloaded;
Route::get('mail', function () { $email = '[email protected]'; Mail::to($email)->send(new FileDownloaded); dd('done'); });
If you head over to Mailtrap, you should see this.
Storage Facade for When Files Already Exist
In an application, it’s not every time we process files through uploads. Sometimes, we decide to defer cloud file uploads till a certain user action is complete. Other times we have some files on disk before switching to a cloud provider. For times like this, Laravel provides a convenient Storage facade. For those who don’t know, facades in Laravel are class aliases. So instead of doing something like Symfony\File\Whatever\Long\Namespace\UploadedFile, we can do Storage instead.
Choosing a disk to upload file. If no disk is specified, Laravel looks in config/filesystems.php and use the default disk.
Storage::disk('local')->exists('file.txt');
use default cloud provider
// Storage::disk('cloud')->exists('file.txt'); will not work so do: Storage::cloud()->exists('file.txt');
Create a new file with contents
Storage::put('file.txt', 'Contents');
Prepend to file
Storage::prepend('file.txt', 'Prepended Text');
Append to file
Storage::append('file.txt', 'Prepended Text');
Get file contents
Storage::get('file.txt')
Check if file exists
Storage::exists('file.txt')
Force file download
Storage::download('file.txt', $name, $headers); // $name and $headers are optional
Generate publicly accessible URL
Storage::url('file.txt');
Generate a temporary public URL (i.e files that won’t exists after a set time). This will only work for cloud providers as Laravel doesn’t yet know how to handle generation of temporary URLs for local disk.
Storage::temporaryUrl('file.txt’, now()->addMinutes(10));
Get file size
Storage::size('file.txt');
Last modified date
Storage::lastModified('file.txt')
Copy files
Storage::copy('file.txt', 'shared/file.txt');
Move files
Storage::move('file.txt', 'secret/file.txt');
Delete files
Storage::delete('file.txt');
// to delete multiple files Storage::delete(['file1.txt', 'file2.txt']);
Manipulating files
Resizing images, adding filters etc. This is where Laravel needs external help. Adding this feature natively to Laravel will only bloat the application since not installs need it. We need a package called intervention/image. We already installed this package, but for reference.
composer require intervention/image
Since Laravel can automatically detect packages, we don't need to register anything. If you are using a version of Laravel lesser than 5.5 read this.
To resize an image
$image = Image::make(storage_path('app/public/profile.jpg'))->resize(300, 200);
Even Laravel's packages are fluent.
You can head over to their website and see all the fancy effects and filters you can add to your image.
Don’t forget directories
Laravel also provides handy helpers to work with directories. They are all based on PHP iterators so they'll provide the utmost performance.
To get all files:
Storage::files
To get all files in a directory including files in sub-folders
Storage::allFiles($directory_name);
To get all directories within a directory
Storage::directories($directory_name);
To get all directories within a directory including files in sub-directories
Storage::allDirectories($directory_name);
Make a directory
Storage::makeDirectory($directory_name);
Delete a directory
Storage::deleteDirectory($directory_name);
Conclusion
If we left anything out, please let us know down in the comments. Also, checkout Mailtrap, they are really good and they will help you sail through the development phase with regards to debugging emails.
via Scotch.io http://ift.tt/2sHlNEp
0 notes
programmingbiters-blog · 7 years ago
Photo
Tumblr media
New Post has been published on https://programmingbiters.com/junior-laravel-developer-programming-interview-test/
Junior Laravel Developer Programming Interview Test
While expanding my team and working with potential junior developers, I’ve come up with a few tasks to test their practical knowledge. There’s not much value in quizzes or interviews – let them create one simple project. From start to finish. So here’s an example of such project, you can use it for your own needs.
We need to test basic Laravel skills, right? So the project should be simple, but at the same time touch majority of fundamentals. Also, it should be possible to do within a day or so – in some cases, you would even pay them for spending their time.
With that in mind, here’s a project I came up with.
Adminpanel to manage companies
Basically, project to manage companies and their employees. Mini-CRM.
Basic Laravel Auth: ability to log in as administrator
Use database seeds to create first user with email [email protected] and password “password”
CRUD functionality (Create / Read / Update / Delete) for two menu items: Companies and Employees.
Companies DB table consists of these fields: Name (required), email, logo (minimum 100×100), website
Employees DB table consists of these fields: First name (required), last name (required), Company (foreign key to Companies), email, phone
Use database migrations to create those schemas above
Store companies logos in storage/app/public folder and make them accessible from public
Use basic Laravel resource controllers with default methods – index, create, store etc.
Use Laravel’s validation function, using Request classes
Use Laravel’s pagination for showing Companies/Employees list, 10 entries per page
Use Laravel make:auth as default Bootstrap-based design theme, but remove ability to register
Basically, that’s it. With this simple exercise junior developer shows the skills in basic Laravel things:
MVC
Auth
CRUD and Resource Controllers
Eloquent and Relationships
Database migrations and seeds
Form Validation and Requests
File management
Basic Bootstrap front-end
Pagination
Guess what – most of the basics web-applications will have these functions as core. There will be a lot more on top of that, but without these fundamentals you cannot move further.
So this task would actually test if the person can create simple projects. And then it’s practice, practice, practice on more projects, each of them individual and adding more to their knowledge base.
From my own experience, different developers are “creative” in different code places – some don’t use Resource controllers and put Route::get everywhere, some don’t validate forms, some don’t test their code properly etc. That’s exactly the things you want to spot as early as possible.
Extra Task for “Advanced” Juniors
If you feel like this task is too small and simple, you can add these things on top:
Use Datatables.net library to show table – with our without server-side rendering
Use more complicated front-end theme like AdminLTE
Email notification: send email whenever new company is entered (use Mailgun or Mailtrap)
Make the project multi-language (using resources/lang folder)
Basic testing with phpunit (I know some would argue it should be the basics, but I disagree)
Do you agree with such task? What would you change or add to this? And have you had any experience with giving similar tasks, what were your impressions?
0 notes
t-baba · 8 years ago
Photo
Tumblr media
What Are the New Features in Laravel 5.5?
Laravel 5.5 will require PHP 7.0+. For the features this modern PHP version brings, please see our recap.
Laravel 5.5 will also be the next LTS (Long Term Support) release. This means bugfixes for two years and three years of security updates. That was also the case with Laravel 5.1, but its two-year window of bug fixes is coming to an end this year. Without further ado, let's see what this new version has to offer.
Creating a New Laravel 5.5 Project
Since the release has not yet officially happened, we can install the dev release version by running the command:
laravel new laravel55 --dev cd laravel55 php artisan key:generate
If you prefer not to use the Laravel installer, you can also take the Composer approach:
composer create-project --prefer-dist --stability=dev laravel/laravel:dev-master cd laravel php artisan key:generate
Once we visit the homepage of the newly set up app, we should be greeted with a welcome page similar to what we used to have in previous Laravel versions.
Rendering Mailables to the Browser
I feel this is something that will come in very handy. In the previous Laravel versions, we had to send actual emails or use an email client like Mailtrap to test email layouts, and this wasn't a fun task. This won't be the case any more, as with Laravel 5.5 it's possible to render the email layout to the browser directly.
A quick walkthrough on how to achieve this: let's create a new mailable as well as the email template for our current project:
php artisan make:mail Welcome --markdown=emails.welcome
I prefer the markdown approach since we will get a template with some content already. Let's open our web.php file and create a test route to checkout the email layout:
Route::get('/email', function () { return new App\Mail\Welcome(); });
routes/web.php
By visiting the route /email we should be able to preview the email template:
What's actually going on under the hood is that with Laravel 5.5, the Mailable class implements the Renderable contract which has a render() method. This is the implementation of the render() method inside lluminate/Mail/Mailable.php:
public function render() { Container::getInstance()->call([$this, 'build']); return Container::getInstance()->make('mailer')->render( $this->buildView(), $this->buildViewData() ); }
lluminate/Mail/Mailable.php
This is the method that makes it possible to get a view. Had we tried returning an instance of a class that does not implement the Renderable contract within our routes, we'd get an UnexpectedValueException thrown.
Custom Email Themes
When using Markdown for emails, Laravel will provide a default theme. However, some people may prefer having some custom styling in their email templates for branding purposes.
To use a custom theme for a particular mailable, we first create a custom .css file containing the styles we want:
touch resources/views/vendor/mail/html/themes/custom.css
We then then specify this filename as a property in the Mailable class:
class Welcome extends Mailable { protected $theme = 'custom'; [...] }
app/Mail/Welcome.php
This way, the email layout will be based on the styles we defined in the custom.css file. The good thing with this approach is that we can have different themes for different mailables.
Exception Helper Functions
Laravel 5.5 comes with two exception helper functions which will help us write more expressive code. The two helpers are the throw_if and throw_unless methods. Both take three arguments with the third argument being optional.
Let's look at the different implementations of these exceptions:
$number = 2; throw_if($number !== 3, new NotThreeException('Number is not three')); // or throw_if($number !== 3, NotThreeException::class, 'Number is not three');
With the throw_if helper, an exception will be thrown if the first argument evaluates to true.
Implementing the throw_unless helper is no different from what we did above, the only difference being that an exception will only be thrown if the first argument evaluates to false:
$number = 2; throw_unless($number === 3, new NotThreeException('Number is not three')); // or throw_unless($number === 3, NotThreeException::class, 'Number is not three');
Not the best example, but serves our demonstration purposes.
Introducing the migrate:fresh Command
You've probably found yourself in a situation that required you to rebuild the database. With previous Laravel versions, we achieved this by running the php artisan migrate:refresh command. The migrate:refresh command rolls back all migrations based on what is specified in the down method for each migration file then runs the migrations again:
But you've probably run into issues with this command a couple of times, especially when working with foreign key constraints or say you have a down() method in one of your migrations that has not been well defined. When that happens, we resort to dropping the table raising issues manually most of the time - (could be from the CLI or some GUI). That's where migrate:fresh comes to our rescue. This command drops all the tables, then runs the existing migrations again:
JSON Error Stack Traces
Not a really big change but then in previous Laravel versions, we'd see HTML markup from an API client such as Postman every time we got an error while building out APIs. In Laravel 5.5, we get a JSON stack trace rather than HTML markup if an error occurs which looks neater and easier to follow:
Automatic Package Discovery
These are the steps we follow in order to use a third party package in our Laravel projects.
Install the package
Register the package's service provider
Register facades if any
As you can see, it could be simpler. Now it is.
With automatic package discovery, we'll just require a package and start using it on the fly. Note, however, this only happens if the package provider has configured the package for autodiscovery.
Looking at the Laravel Debugbar package which has already been updated for package autodiscovery, we see that there is an extra section inside the composer.json file:
"extra": { "laravel": { "providers": [ "Foo\\Bar\\ServiceProvider" ], "aliases": { "Bar": "Foo\\Bar\\Facade" } } }
Package providers will have to update the composer.json file with an extra section, then specify the providers and any aliases for the package.
Another good thing with automatic package discovery is that things won't break after removing a dependency. Normally, even after uninstalling a package we still have the package's service providers and facades hanging around in the config/app.php file and this may raise issues in some cases.
With package autodiscovery, when a package is removed via Composer, then everything related to the package is also removed.
Continue reading %What Are the New Features in Laravel 5.5?%
by Christopher Vundi via SitePoint http://ift.tt/2u5b5aV
0 notes
gadherkeyur · 5 years ago
Text
How To Use Laravel Mailtrap To Send Email?
How To Use Laravel Mailtrap To Send Email?
[vc_row][vc_column][vc_column_text]
Sending mails in a different account (user emails) for testing in the local server is a headache. Every time you need to send an email through the same email or ask a colleague to check an email. Today you are going to learn laravel mailtrap to get rid of this. You can send mail into any email address and receive into mailtrap inbox. So, lets get started.
[/vc_…
View On WordPress
0 notes
mbaljeetsingh · 8 years ago
Text
What Are the New Features in Laravel 5.5?
Laravel 5.5 will require PHP 7.0+. For the features this modern PHP version brings, please see our recap.
Laravel 5.5 will also be the next LTS (Long Term Support) release. This means bugfixes for two years and three years of security updates. That was also the case with Laravel 5.1, but its two-year window of bug fixes is coming to an end this year. Without further ado, let's see what this new version has to offer.
Creating a New Laravel 5.5 Project
Since the release has not yet officially happened, we can install the dev release version by running the command:
laravel new laravel55 --dev cd laravel55 php artisan key:generate
If you prefer not to use the Laravel installer, you can also take the Composer approach:
composer create-project --prefer-dist --stability=dev laravel/laravel:dev-master cd laravel php artisan key:generate
Once we visit the homepage of the newly set up app, we should be greeted with a welcome page similar to what we used to have in previous Laravel versions.
Rendering Mailables to the Browser
I feel this is something that will come in very handy. In the previous Laravel versions, we had to send actual emails or use an email client like Mailtrap to test email layouts, and this wasn't a fun task. This won't be the case any more, as with Laravel 5.5 it's possible to render the email layout to the browser directly.
A quick walkthrough on how to achieve this: let's create a new mailable as well as the email template for our current project:
php artisan make:mail Welcome --markdown=emails.welcome
I prefer the markdown approach since we will get a template with some content already. Let's open our web.php file and create a test route to checkout the email layout:
Route::get('/email', function () { return new App\Mail\Welcome(); });
routes/web.php
By visiting the route /email we should be able to preview the email template:
What's actually going on under the hood is that with Laravel 5.5, the Mailable class implements the Renderable contract which has a render() method. This is the implementation of the render() method inside lluminate/Mail/Mailable.php:
public function render() { Container::getInstance()->call([$this, 'build']); return Container::getInstance()->make('mailer')->render( $this->buildView(), $this->buildViewData() ); }
lluminate/Mail/Mailable.php
This is the method that makes it possible to get a view. Had we tried returning an instance of a class that does not implement the Renderable contract within our routes, we'd get an UnexpectedValueException thrown.
Custom Email Themes
When using Markdown for emails, Laravel will provide a default theme. However, some people may prefer having some custom styling in their email templates for branding purposes.
To use a custom theme for a particular mailable, we first create a custom .css file containing the styles we want:
touch resources/views/vendor/mail/html/themes/custom.css
We then then specify this filename as a property in the Mailable class:
class Welcome extends Mailable { protected $theme = 'custom'; [...] }
app/Mail/Welcome.php
This way, the email layout will be based on the styles we defined in the custom.css file. The good thing with this approach is that we can have different themes for different mailables.
Exception Helper Functions
Laravel 5.5 comes with two exception helper functions which will help us write more expressive code. The two helpers are the throw_if and throw_unless methods. Both take three arguments with the third argument being optional.
Let's look at the different implementations of these exceptions:
$number = 2; throw_if($number !== 3, new NotThreeException('Number is not three')); // or throw_if($number !== 3, NotThreeException::class, 'Number is not three');
With the throw_if helper, an exception will be thrown if the first argument evaluates to true.
Implementing the throw_unless helper is no different from what we did above, the only difference being that an exception will only be thrown if the first argument evaluates to false:
$number = 2; throw_unless($number === 3, new NotThreeException('Number is not three')); // or throw_unless($number === 3, NotThreeException::class, 'Number is not three');
Not the best example, but serves our demonstration purposes.
Introducing the migrate:fresh Command
You've probably found yourself in a situation that required you to rebuild the database. With previous Laravel versions, we achieved this by running the php artisan migrate:refresh command. The migrate:refresh command rolls back all migrations based on what is specified in the down method for each migration file then runs the migrations again:
But you've probably run into issues with this command a couple of times, especially when working with foreign key constraints or say you have a down() method in one of your migrations that has not been well defined. When that happens, we resort to dropping the table raising issues manually most of the time - (could be from the CLI or some GUI). That's where migrate:fresh comes to our rescue. This command drops all the tables, then runs the existing migrations again:
JSON Error Stack Traces
Not a really big change but then in previous Laravel versions, we'd see HTML markup from an API client such as Postman every time we got an error while building out APIs. In Laravel 5.5, we get a JSON stack trace rather than HTML markup if an error occurs which looks neater and easier to follow:
Automatic Package Discovery
These are the steps we follow in order to use a third party package in our Laravel projects.
Install the package
Register the package's service provider
Register facades if any
As you can see, it could be simpler. Now it is.
With automatic package discovery, we'll just require a package and start using it on the fly. Note, however, this only happens if the package provider has configured the package for autodiscovery.
Looking at the Laravel Debugbar package which has already been updated for package autodiscovery, we see that there is an extra section inside the composer.json file:
"extra": { "laravel": { "providers": [ "Foo\\Bar\\ServiceProvider" ], "aliases": { "Bar": "Foo\\Bar\\Facade" } } }
Package providers will have to update the composer.json file with an extra section, then specify the providers and any aliases for the package.
Another good thing with automatic package discovery is that things won't break after removing a dependency. Normally, even after uninstalling a package we still have the package's service providers and facades hanging around in the config/app.php file and this may raise issues in some cases.
With package autodiscovery, when a package is removed via Composer, then everything related to the package is also removed.
Continue reading %What Are the New Features in Laravel 5.5?%
via SitePoint http://ift.tt/2wmD171
0 notes